package com.warthur.jfinal.demo.controller;

import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.json.FastJson;
import com.jfinal.render.RenderManager;
import com.warthur.jfinal.demo.common.ErrorCode;
import com.warthur.jfinal.demo.common.Response;
import com.warthur.jfinal.demo.common.ResponseUtils;

import java.util.Set;

/**
 * @author warthur
 * @date 2019/10/07
 */
public class BaseController extends Controller {

    @Override
    @NotAction
    public void renderJson(Object object) {
        if (object instanceof Response) {
            super.renderJson(object);
            return;
        }
        Response response = ResponseUtils.success(object);
        super.renderJson(response);
    }

    @Override
    @NotAction
    public void renderJson(String message) {
        Response response = ResponseUtils.error(message);
        renderJson(response);
    }

    @NotAction
    public void renderError(ErrorCode errorCode, Object data) {
        Response response = ResponseUtils.error(errorCode, data);
        renderJson(response);
    }

    @NotAction
    public void renderError(int status, ErrorCode errorCode) {
        Response response = ResponseUtils.error(errorCode);
        renderError(status, RenderManager.me().getRenderFactory().getJsonRender(response));
    }

    @NotAction
    public void renderError(int status, ErrorCode errorCode, Object data) {
        Response response = ResponseUtils.error(errorCode, data);
        renderError(status, RenderManager.me().getRenderFactory().getJsonRender(response));
    }

    @NotAction
    public void renderError(int status, Set<String> set) {
        Response response = ResponseUtils.error(String.join("，", set));
        renderError(status, RenderManager.me().getRenderFactory().getJsonRender(response));
    }

    @NotAction
    public <T> T getJsonBody(Class<T> clazz) {
        return FastJson.getJson().parse(getRawData(), clazz);
    }
}
